/*
		ServEngine framework library
		A library to fast develop JEE online applications
	
		Copyright 2008 José Ignacio de Córdoba Álvaro

		Licensed under the Apache License, Version 2.0 (the "License");
		you may not use this file except in compliance with the License.
		You may obtain a copy of the License at

				http://www.apache.org/licenses/LICENSE-2.0

		Unless required by applicable law or agreed to in writing, software
		distributed under the License is distributed on an "AS IS" BASIS,
		WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
		See the License for the specific language governing permissions and
		limitations under the License.
	
		Jose Ignacio de Cordoba Alvaro
		http://ignacio.decordoba.com
*/

package com.servengine.user;

import com.servengine.portal.Portal;
import com.servengine.util.ServletContextUtils;
// Hay que pasar también esto a la capa cliente. Ahora está en servidor (!!!)

import java.rmi.RemoteException;

import java.util.ArrayList;
import java.util.Collection;

import java.util.List;

import java.util.Locale;

import javax.ejb.FinderException;


import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;

public class UserSessionSBean implements java.io.Serializable,Comparable<UserSessionSBean>,HttpSessionBindingListener
{
	protected static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(UserSession.class.getName());
	protected UserSession userSession;
	protected HttpSession httpSession;
	protected ServletContextUtils servletContextUtils;
	protected boolean hasPicture;
	
/*	public UserSessionSBean(User user)
	{
		this.user=user;
		starttime = new java.util.Date();
	}*/
	public UserSessionSBean(UserSession userSession)
	{
		this.userSession=userSession;
	}
	public void valueBound(HttpSessionBindingEvent event)
	{
		httpSession = event.getSession();
	  servletContextUtils = (com.servengine.util.ServletContextUtils)httpSession.getServletContext().getAttribute(ServletContextUtils.SERVLETCONTEXT_ATTRIBUTE_NAME);
	}
	public void valueUnbound(HttpSessionBindingEvent event)
	{
//		userSession.setEnd(new java.util.Date());// Esto no vale para nada puesto que no se hace persist de ese objeto.
	}
	public String getPortalid()
	{
		return userSession.getPortalid();
	}
	public String getUserid()
	{
		return userSession.getUserid();
	}
	public Integer getId()
	{
		return userSession.getId();
	}
	public java.util.Date getStart()
	{
		return userSession.getStart();
	}
	public java.util.Date getEnd()
	{
		return userSession.getEnd();
	}
	public int compareTo(UserSessionSBean o)
	{
		int resultado = -getStart().compareTo(o.getStart()); // Ojo al signo menos. La última sesión será "menor" que las antiguas.
		return resultado==0?1:resultado;
	}
	protected Object getExpensiveDatum(String key)
	{
		return servletContextUtils.getExpensiveDatum(userSession.getPortalid(),key);
	}
	public Integer getUserCount() // TODO ¿Esto no se puede hacer por introspección?
	{
		return (Integer)getExpensiveDatum("userCount");
	}
	public Collection<UserSessionSBean> getOnlineUserSessions()
	{
		return servletContextUtils.getOnlineUserSessions(userSession.getPortalid());
	}

	public Collection<UserSessionSBean> getOnlineAuthentifiedUserSessions()
	{
		return servletContextUtils.getOnlineAuthentifiedUserSessions(userSession.getPortalid());
	}
	public Collection<UserSessionSBean> getOnlineGuestUserSessions()
	{
		return servletContextUtils.getOnlineGuestUserSessions(userSession.getPortalid());
	}
	public boolean isAdmin()
	{
		return userSession.getUser().isAdmin();
/*		for (Role role: userSession.getUser().getRoles())
			if (role.getName().equals("admin"))
				return true;
		return false;*/
	}
	public boolean isGuest()
	{
		return userSession.getUser().isGuest();
	}
	public User getUser()
	{
		return userSession.getUser();
	}
	public Portal getPortal()
	{
		return userSession.getUser().getPortal();
	}
	public void refresh(Portal portal)
	{
		if (!userSession.getPortalid().equals(portal.getId()))
			throw new IllegalArgumentException();
		userSession.getUser().setPortal(portal);
	}
	public void refresh(User user)
	{
		if (!userSession.getPortalid().equals(user.getPortal().getId()))
			throw new IllegalArgumentException();
		userSession.setUser(user);
	}
	/**
	 * @deprecated User directly getPortal().getServiceNames()
	 * @return
	 */
	public Collection<String> getServiceNames()
	{
		return userSession.getUser().getPortal().getServiceNames();
	}
	
	public int getNewUserCount() throws FinderException,RemoteException
	{
	  return servletContextUtils.getUserManager().getNewUsers(getPortalid(), userSession.getUser().getLastLogin()).size();
	}
	public List<User> getLastUsers() throws FinderException,RemoteException
	{
		return servletContextUtils.getUserManager().getLastUsers(getPortalid());
	}
	public List<UserSession> getLastUserSessions() throws FinderException,RemoteException
	{
		return servletContextUtils.getUserManager().getLastUserSessions(getPortalid());
	}
	protected  Collection<String> getLoginMessages() throws RemoteException,FinderException
	{
		Collection<String> messages = new ArrayList<String>();
		for (Role role: userSession.getUser().getPortal().getRoles())
			if (role.getLoginText()!=null)
				messages.add(role.getLoginText());
		return messages;
	}

	public void setHasPicture(boolean hasPicture)
	{
		this.hasPicture = hasPicture;
	}

	public boolean isHasPicture()
	{
		return hasPicture || userSession.getUser().isHasPicture();
	}
	
	public long getNewMessageCount() throws RemoteException,FinderException
	{
		return (int)servletContextUtils.getEntryManager().getNewEntryCount(getPortalid(),"user","message",getUser().getId(),getStart());
	}

	public UserSession getUserSession()
	{
		return userSession;
	}
	public Locale getLocale()
	{
		String locale = null;
		if (userSession.getUser().getLocale()==null)
			locale = userSession.getUser().getPortal().getLocale();
		else
			locale = userSession.getUser().getLocale();
		try
		{
			return locale == null?null:(locale.indexOf("_")==-1?new Locale(locale):new Locale(locale.split("_")[0],locale.split("_")[1]));
		} catch (Throwable e)
		{
			log.error(e.getMessage(),e);
			return null;
		}
	}
	public HttpSession getHttpSession()
	{
		return httpSession;
	}
}
